package com.lepu.app.fun.my;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.core.lib.widget.GoogleRefreshLayout.OnScrollListener;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.my.adapter.AdapterFensi;
import com.lepu.app.fun.my.bean.BeanFensi;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class MyFenSiActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest, OnRefreshListener,
		OnLoadListener,OnScrollListener {

	public static final int TYPE_FENSI = 1;
	public static final int TYPE_GUANZHU = 2;

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final String REQUEST_ADD_GUAN_ZHU = "request_add_guan_zhu";
	private static final String REQUEST_CANCEL_GUAN_ZHU = "request_cancel_guan_zhu";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;

	public GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private AdapterFensi mDataAdapter = null;
	private ArrayList<BeanFensi> mDataArrayList = null;
	private int mCurrentPage = 1;

	private int mType = 0;
	private String mTargetUserID = "0";
	
	private int mCurrentOpePosition = 0;
	private boolean mCurrentOpe = false;
	private boolean mIsSelfUserID = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_fensi_activity);

		init();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	private void init() {

		Bundle data = getIntent().getExtras();
		if (data != null && data.size() > 0)
		{
			mType = data.getInt("fensi_guanzhu");
			mTargetUserID = data.getString("TargetUserID");
		}

		if(!TextUtils.isEmpty(mTargetUserID) && mTargetUserID.equals(LoginUtil.getUserId())){
			mIsSelfUserID = true;
		}else{
			mIsSelfUserID = false;
		}

		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setonTopbarNewLeftLayoutListener(this);

		if (mType == TYPE_FENSI) {
			topbar.setTopbarTitle("粉丝");
		} else if (mType == TYPE_GUANZHU) {
			topbar.setTopbarTitle("关注");
		} else {
			topbar.setTopbarTitle("");
		}

		mDataListView = (ListView) findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setOnScrollListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);
		
		showFirstLoadDataLayout(true);
		request(false);
	}

	// 请求数据
	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
		}

//		 String url = Setting.getTestJsonUrl(page);
//		 ApiClient.http_get(url, this, request);

		String url = Setting.getMyFensiAndGuanZhuUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID",
					MyApplication.getInstance().getLoginInfo().UserID);
			params.put("LoginToken",
					MyApplication.getInstance().getLoginInfo().LoginToken);

			params.put("Relation", mType);
			params.put("TargetUserID", mTargetUserID);
			
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true, false, true);
	}

	/**
	 * 添加关注
	 * @param item
	 */
	public void addGuanZhu(BeanFensi item,int position) {
		
		if(mCurrentOpe)
		{
			return;
		}
			
		mCurrentOpe = true;
		mCurrentOpePosition = position;
		
		String url = Setting.getUserFollowUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID",
					MyApplication.getInstance().getLoginInfo().UserID);
			params.put("LoginToken",
					MyApplication.getInstance().getLoginInfo().LoginToken);

			params.put("TargetUserID", item.UserID);
			
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(url, map, null, this, REQUEST_ADD_GUAN_ZHU, true);
	}
	
	/**
	 * 取消关注
	 * @param item
	 */
	public void cancelGuanZhu(final BeanFensi item,final int position) {
		
		if(mCurrentOpe)
		{
			return;
		}

		String message = "您确定取消关注吗？";
		MyDialog dialog = new MyDialog(this)
				.setMessage(message)
				.setNegativeButton(R.string.app_cancel,
						R.drawable.btn_cancel_selector, R.color.color_white,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_ok,
						R.drawable.btn_ok_selector, R.color.color_white,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

								mCurrentOpe = true;
								mCurrentOpePosition = position;

								String url = Setting.getUserFollowCancelUrl();

								Map<String, Object> map = new HashMap<String, Object>();
								JSONObject params = new JSONObject();
								try {
									params.put("DeviceID", Setting.DEVICEID);
									params.put("ApplicationID", Setting.APPLICATIONID);

									params.put("UserID",
											MyApplication.getInstance().getLoginInfo().UserID);
									params.put("LoginToken",
											MyApplication.getInstance().getLoginInfo().LoginToken);

									params.put("TargetUserID", item.UserID);

								} catch (Exception e) {
								}
								map.put("ht", params);
								ApiClient.http_post_main(url, map, null, MyFenSiActivity.this, REQUEST_CANCEL_GUAN_ZHU, true);
							}
						});

		dialog.create(null);
		dialog.showMyDialog();
	}
	
	private void showHideNoDataLayout(boolean isShow) {
		LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
		if (noDataLayout != null) {
			if (isShow) {
				noDataLayout.setVisibility(View.VISIBLE);
			} else {
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}

	private void showFirstLoadDataLayout(boolean isShow) {
		LinearLayout firstLoadDataLayout = (LinearLayout) findViewById(R.id.firstLoadDataLayout);
		if (firstLoadDataLayout != null) {
			if (isShow) {
				if (mDataArrayList == null || mDataArrayList.size() == 0) {
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}
				
				LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);

			} else {
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:

				ArrayList<BeanFensi> dataList = (ArrayList<BeanFensi>) msg.obj;
				if (dataList != null && dataList.size() > 0) {

					mDataArrayList = dataList;

					showHideNoDataLayout(false);
				} else {
//					UIHelper.showToast(MyApplication.getInstance(),
//							R.string.no_data);

					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}
					showHideNoDataLayout(true);
				}

				if (mDataArrayList == null) {
					mDataArrayList = new ArrayList<BeanFensi>();
				}

				ImageView tempImageView = new ImageView(MyFenSiActivity.this);
				mDataListView.addHeaderView(tempImageView);

				mDataAdapter = new AdapterFensi(MyFenSiActivity.this,
						mDataArrayList,mType,mIsSelfUserID);
				mDataListView.setAdapter(mDataAdapter);

				mDataListView.removeHeaderView(tempImageView);

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);

				// 第一次请求用这个
				showFirstLoadDataLayout(false);

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);

				showFirstLoadDataLayout(false);
				showHideNoDataLayout(true);
				break;
			case MSG_DATA_MORE_SUCCESS:

				ArrayList<BeanFensi> dataMoreList = (ArrayList<BeanFensi>) msg.obj;
				if (dataMoreList != null && dataMoreList.size() > 0) {
					mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(MyApplication.getInstance(),
							R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		request(false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			// 解析json data
			ArrayList<BeanFensi> dataArraylist = BeanFensi
					.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			// 解析json data more
			ArrayList<BeanFensi> dataMoreArraylist = BeanFensi
					.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				for (int i = 0; i < dataMoreArraylist.size(); i++) {
					BeanFensi item = dataMoreArraylist.get(i);
					mDataArrayList.add(item);
				}
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_ADD_GUAN_ZHU)) {
			
			mCurrentOpe = false;
			
			String result = (String) data;
			int FollowStatus = 0;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject dataObject = (JSONObject) obj1.get("DetailInfo");
				FollowStatus = dataObject.getInt("FollowStatus");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			ImageButton opeImageButton = (ImageButton) mDataListView.findViewWithTag(mCurrentOpePosition);
			if(opeImageButton != null)
			{
				mDataArrayList.get(mCurrentOpePosition).FollowStatus = FollowStatus;
				if(FollowStatus == BeanFensi.STATUS_1)
				{
					opeImageButton.setBackgroundResource(R.drawable.my_fensi_icon_finish_guanzhu);
				}else if(FollowStatus == BeanFensi.STATUS_2){
					opeImageButton.setBackgroundResource(R.drawable.my_fensi_icon_xianghu_guanzhu);
				}
			}
		}else if (object.equals(REQUEST_CANCEL_GUAN_ZHU)) {
			mCurrentOpe = false;
			
			ImageButton opeImageButton = (ImageButton) mDataListView.findViewWithTag(mCurrentOpePosition);
			if(opeImageButton != null)
			{
				mDataArrayList.get(mCurrentOpePosition).FollowStatus = BeanFensi.STATUS_3;
				opeImageButton.setBackgroundResource(R.drawable.my_fensi_icon_add_guanzhu);
			}
		} 
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		} else if (object.equals(REQUEST_ADD_GUAN_ZHU)) {
			mCurrentOpe = false;
		} else if (object.equals(REQUEST_CANCEL_GUAN_ZHU)) {
			mCurrentOpe = false;
		} 
	}
	
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		LogUtilBase.LogD(null,"onScrollStateChanged");
	}
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		
		StringBuffer sb = new StringBuffer();
		sb.append("firstVisibleItem===");
		sb.append(firstVisibleItem);
		sb.append("\n");
		
		sb.append("visibleItemCount===");
		sb.append(visibleItemCount);
		sb.append("\n");
		
		LogUtilBase.LogD(null,"onScrollStateChanged ===>> "+sb.toString());
	}

}
